package com.ls.stack;

import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * @program: dataStructure
 * @author: lishun
 * @create: 2021-12-07 17:16
 **/
// 逆波兰实现计算器


/**|     String express = "34 + 5 × 6 -";
 * 1. 从左至右扫描，将3和4压入堆栈;
 * 2. 遇到+运算符，因此弹出4和3(4为栈顶元素，3为次顶元素），计算出3+4的值，得7，再将7入栈;
 * 3. 将5入栈;
 * 4. 接下来是×运算符，因此弹出5和7，计算出7×5=35，将35入栈;5)将6入栈;
 * 5. 最后是-运算符，计算出35-6的值，即29，由此得出最终结果；
 */

@Data
@ToString
@RequiredArgsConstructor
public class ReversePolishCalculator {
    LinkStack<String> linkStack = new LinkStack<>();

    public static void main(String[] args) {
        String express = "3 4 + 5 * 6 -";
        ReversePolishCalculator reversePolishCalculator = new ReversePolishCalculator();
        int res = reversePolishCalculator.calculate(express);
        System.out.println(res);
    }

    public int calculate(String express){
        String[] arr =  StringToArray(express);
        for (String s : arr) {
            if (s.matches("\\d+")){
                // 匹配到的是数字直接入栈
                linkStack.push(s);
            }else {
                Integer num1 = Integer.parseInt(linkStack.pop());
                Integer num2 = Integer.parseInt(linkStack.pop());
                int result = cal(num2, num1, s);
                linkStack.push(result+"");
            }
        }
        return Integer.parseInt(linkStack.pop());
    }

    private String[] StringToArray(String express) {
        return express.split(" ");
    }
    public int cal(int num1,int num2,String sym){
        switch (sym){
            case "*":
                return num1 * num2;
            case "/":
                return num1 / num2;
            case "+":
                return num1 + num2;
            case "-":
                return num1 - num2;
            default:
                throw new RuntimeException("不支持的表达式："+sym);
        }
    }

}
